
import process from './mockFlag.js';
import store from '@/store'

let common_ajax_url = 'http://218.65.83.72:8099';//http://218.65.83.72:8099  http://218.65.83.70:60119   http://192.168.96.70:8080/

if(process.env.MOCK)
	// common_ajax_url = 'http://192.168.0.151:3003'; //公司
	common_ajax_url = 'http://192.168.1.10:3003';


export default {
  ajax (url, data={}, type='POST') {
		// let pid = store.state.pid;
		let pid = uni.getStorageSync('zuipid');
		if(process.env.MOCK){
			pid = 'test';
		}
		if(url.indexOf('/rest/baseLogin') < 0 ) {
			if(!pid){
				uni.showModal({
					title: '医内物流',
					content: '登录超时',
					showCancel: false,
					success: function () {
						uni.reLaunch({
							url: '/pages/login/index'
						});
					}
				});
			}
		}
		
		/* let userInfoAll = uni.getStorageSync('userInfoAll'),
			token = null;
		if(userInfoAll){
			userInfoAll = JSON.parse(userInfoAll);
			token = userInfoAll.token;
		} */
		
		const zdata = data;
		// 空值转为null
		for(var key in zdata){
			if(zdata[key] == undefined || zdata[key] == null || zdata[key].toString() == '')
				zdata[key] = null;
		}
		
		if(process.env.MOCK)
			type = 'GET';
		
		return new Promise(function(resolve, reject) {
			uni.request({
				url: common_ajax_url + url,
				data: zdata,
				method: type,
				header: {
					'X-Requested-With': 'XMLHttpRequest',
					// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
					'Content-Type': 'application/json; charset=UTF-8',
					'pid': pid
				},
				success (res) {
					if (res.statusCode == 200) {
						if(process.env.MOCK)
							resolve(res.data.body);
						else
							resolve(res);
					} else {
						resolve(res);
						// console.log(JSON.stringify(res))
					}
				},
				fail (res) {
					if(res.description && res.description.indexOf('timeout') !== -1){
						uni.showModal({
							title: '院内物流',
							content: url+"请求超时，请稍后再试",
							showCancel: false
						});
					}else if(res.description && res.description.indexOf('request') !== -1){
						uni.showModal({
							title: '院内物流',
							content: "服务器已关闭",
							showCancel: false
						});
					}else{
						uni.showModal({
							title: '院内物流',
							content: "请检查网络后重试",
							showCancel: false
						});
					}
					if(uni.getSystemInfoSync().platform == 'ios'){
						uni.vibrateShort({
							success: function () {}
						});
					}else{
						uni.vibrateLong({
							success: function () {}
						});
					}
					try{
						uni.hideLoading();
					}catch(e){
						//TODO handle the exception
					}
				},
				complete () {
					/* try{
						uni.hideLoading();
					}catch(e){
						//TODO handle the exception
					} */
				}
			});
		})
  }
}